import requests
import json
from common.log import logger

support_method = "get, post, delete, put"


class RequestMethodError(Exception):
    def __init__(self, method_name):
        self.method_name = method_name

    def __str__(self):
        logger.error(f"[{self.__class__.__name__}] Can't send the request with method {self.method_name}")
        logger.error(f"[{self.__class__.__name__}] This class only supports {support_method} method request")


class RequestURLError(Exception):
    def __init__(self):
        pass

    def __str__(self):
        logger.error(f"[{self.__class__.__name__}] Can't send the request without url")


class HTTPRequest(object):
    def __get_request(self, url: str, headers: dict, params: dict, cookies: dict, timeout: "float or tuple"):
        response = requests.get(url, params, headers=headers, cookies=cookies, timeout=timeout)
        if response.status_code == 200:
            return {"code": "000", "message": "GET请求处理成功",
                    "data": {"status_code": response.status_code, "text": response.text,
                             "cookies": response.cookies.get_dict(),
                             "duration": response.elapsed.microseconds / 1000}}
        else:
            return {"code": "900", "message": "GET请求处理失败", "data": {"status_code": str(response.status_code), "text": response.text}}

    def __post_request(self, url: str, headers: dict, params: dict, cookies: dict, timeout: "float or tuple"):
        # logger.debug(f"发送{url} post请求前cookies: {cookies}")
        response = requests.post(url, json=params, headers=headers, cookies=cookies, timeout=timeout)
        # logger.debug(f"发送{url} post请求后cookies: {response.cookies}")
        if response.status_code == 200:
            return {"code": "000", "message": "POST请求处理成功",
                    "data": {"status_code": response.status_code, "text": response.text,
                             "cookies": response.cookies.get_dict(),
                             "duration": response.elapsed.microseconds / 1000}}
        else:
            return {"code": "900", "message": "POST请求处理失败",
                    "data": {"status_code": str(response.status_code), "text": response.text}}

    def __delete_request(self, url: str, headers: dict, params: dict, cookies: dict, timeout: "float or tuple"):
        response = requests.delete(url, json=params, headers=headers, cookies=cookies, timeout=timeout)
        if response.status_code == 200:
            return {"code": "000", "message": "DELETE请求处理成功",
                    "data": {"status_code": response.status_code, "text": response.text,
                             "cookies": response.cookies.get_dict(),
                             "duration": response.elapsed.microseconds / 1000}}
        else:
            return {"code": "500", "message": "DELETE请求处理失败",
                    "data": {"status_code": str(response.status_code), "text": response.text}}

    def __put_request(self, url: str, headers: dict, params: dict, cookies: dict, timeout: "float or tuple"):
        response = requests.put(url, json=params, headers=headers, cookies=cookies, timeout=timeout)
        if response.status_code == 200:
            return {"code": "000", "message": "PUT请求处理成功",
                    "data": {"status_code": response.status_code, "text": response.text,
                             "cookies": response.cookies.get_dict(),
                             "duration": response.elapsed.microseconds / 1000}}
        else:
            return {"code": "500", "message": "PUT请求处理失败",
                    "data": {"status_code": str(response.status_code), "text": response.text}}

    def http_request(self, method: str, url: str, headers: dict, params: dict, cookies: dict = None,
                     timeout: "float or tuple" = (5, 10)):
        result = {}
        try:
            if url == "":
                result = {"code": "400", "message": "请求地址为空", "data": {}}
            elif url != "":
                if not isinstance(headers, dict) and headers != "" and headers is not None:
                    headers = json.loads(headers)
                if not isinstance(params, dict) and params != "" and params is not None:
                    params = json.loads(params)
                if not isinstance(cookies, dict) and cookies != "" and cookies is not None:
                    cookies = json.loads(cookies)
                if method not in ["get", "post", "delete", "put", "GET", "POST", "DELETE", "PUT"]:
                    result = {"code": "400", "message": "请求类型错误", "data": {}}
                elif method in ["get", "GET"]:
                    result = self.__get_request(url, headers, params, cookies, timeout)
                elif method in ["post", "POST"]:
                    result = self.__post_request(url, headers, params, cookies, timeout)
                elif method in ["delete", "DELETE"]:
                    result = self.__delete_request(url, headers, params, cookies, timeout)
                elif method in ["put", "PUT"]:
                    result = self.__put_request(url, headers, params, cookies, timeout)
            else:
                result = {"code": "400", "message": "请求地址类型错误", "data": {}}
        except Exception as e:
            result = {"code": "500", "message": f"{e}", "data": {}}
        logger.info(url)
        return result


if __name__ == "__main__":
    request = HTTPRequest()
    response = request.http_request("post", "http://jetflow.mynetgear.com:58001/api/login",
                                    {"content-type": "application/json"},
                                    {"name": "admin", "password": "7488e331b8b64e5794da3fa4eb10ad5d"})
    print(response)
